package com.ys.service.storage.impl;

import com.ys.dto.AddDto;
import com.ys.entity.storage.*;
import com.ys.enume.storage.TccFbaDeliverEnum;
import com.ys.enume.storage.TccLogisticsComprehensiveEnum;
import com.ys.enume.storage.TccLogisticsMethodEnum;
import com.ys.enume.storage.TccLogisticsMethodItemEnum;
import com.ys.mapper.storage.StorageMapper;
import com.ys.mapper.storage.TccFbaDeliverMapper;
import com.ys.mapper.storage.TccLogisticsComprehensiveMapper;
import com.ys.service.storage.TccLogisticsComprehensiveOrderService;
import com.ys.service.storage.TccLogisticsPlanService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.FbaUtils;
import com.ys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: fxz
 * @CreateTime: 2025-02-26
 * @Description: 物流计划单实现类
 * @Version: 1.0
 */
@Service("tccLogisticsPlanService")
public class TccLogisticsPlanServiceImpl implements TccLogisticsPlanService {

    @Autowired
    private StorageMapper storageMapper;

    @Autowired
    private CommonApiService<TccLogisticsComprehensive> commonApiService;

    @Autowired
    private TccLogisticsComprehensiveMapper tccLogisticsComprehensiveMapper;

    @Autowired
    private TccFbaDeliverMapper tccFbaDeliverMapper;

    @Autowired
    private TccLogisticsComprehensiveOrderService tccLogisticsComprehensiveOrderService;

    /**
     * 单独发货标记
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R ssmark(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<Long> idList = new HashSet<>();
        for(String id : strs){
            idList.add(Long.valueOf(id));
        }
        //批量勾选“FBA发货单号”（FBA单条默认整个发货单号都选到）
        String fbaDeliverIds = "";
        for (Long id :idList){
            if ("".equals(fbaDeliverIds)) {
                fbaDeliverIds =  id.toString();
            }else {
                fbaDeliverIds = fbaDeliverIds + "," + id;
            }
        }
        int count = storageMapper.logsticsWayCount(fbaDeliverIds);
        if (count > 1){
            return R.error("勾选的发货单中，物流服务需要一致，请确认；");
        }
//        int countNameCle = storageMapper.logsticsNameLogsticsClearanceCount(fbaDeliverIds);
//        if (countNameCle > 0){
//            return R.error("单独发货的清关方式只能是自税，请确认；");
//        }

        //查询是否重复或者不重复数据（是否绑定数据）
        Map<String,String> map = new HashMap<String, String>();
        //是否重复
        boolean isRepetition = false;
        //是否需要选择渠道服务
        boolean isChannel = false;
        List<TccLogisticsPlanAlone> tccLogisticsPlanAloneList = storageMapper.tccLogisticsPlanAloneList(fbaDeliverIds);
        for (TccLogisticsPlanAlone tccLogisticsPlanAlone : tccLogisticsPlanAloneList){
            String joint = tccLogisticsPlanAlone.getVgsbm() + tccLogisticsPlanAlone.getCck() + tccLogisticsPlanAlone.getFbaWarehouse()
                    +tccLogisticsPlanAlone.getTransportationId();
            if (map.get(joint) != null){
                if (isRepetition == false){
                    isRepetition = true;
                }
            }else {
                map.put(joint,tccLogisticsPlanAlone.getFbaDeliverId().toString());
            }
            if (isChannel == false){
                if (tccLogisticsPlanAlone.getLogsticsWay() == null){
                    isChannel = true;
                }
            }

        }

        Map<String,String> mapBoolean = new HashMap<String, String>();
        mapBoolean.put("cck",tccLogisticsPlanAloneList.get(0).getCck());
        mapBoolean.put("destinationCountryCode",tccLogisticsPlanAloneList.get(0).getDestinationCountryCode());
        mapBoolean.put("transportationId",tccLogisticsPlanAloneList.get(0).getTransportationId().toString());
        mapBoolean.put("nameLogsticsClearance",tccLogisticsPlanAloneList.get(0).getNameLogsticsClearance());
        mapBoolean.put("isRepetition",isRepetition+"");
        mapBoolean.put("isChannel",isChannel+"");
        return R.ok(mapBoolean);
    }

    /**
     * 单独发货标记
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R ssmarkNew(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<Long> idList = new HashSet<>();
        for(String id : strs){
            idList.add(Long.valueOf(id));
        }
        //批量勾选“FBA发货单号”（FBA单条默认整个发货单号都选到）
        String fbaDeliverIds = "";
        for (Long id :idList){
            if ("".equals(fbaDeliverIds)) {
                fbaDeliverIds =  id.toString();
            }else {
                fbaDeliverIds = fbaDeliverIds + "," + id;
            }
        }

        //查询是否重复或者不重复数据（是否绑定数据）
        Map<String,String> map = new HashMap<String, String>();
        //是否需要设置物流渠道的数据
        Map<String,String> mapNew = new HashMap<String, String>();
        List<TccLogisticsPlanAlone> tccLogisticsPlanAloneList = storageMapper.tccLogisticsPlanAloneList(fbaDeliverIds);

        TccLogisticsChannelMaint tccLogisticsChannelMaint = new TccLogisticsChannelMaint().setId(Long.valueOf(params.get("logsticsChannelId").toString())).queryFirst();
        if (tccLogisticsChannelMaint.getCoefficientWeight() == 0) {
            tccLogisticsChannelMaint.setCoefficientWeight(5000);
        } else {
            tccLogisticsChannelMaint.setCoefficientWeight(6000);
        }

        List<TccAdditionalBillingMaintTwo> tccAdditionalBillingMaintList = new TccAdditionalBillingMaintTwo().setMethodId(tccLogisticsChannelMaint.getId()).queryList();

        //获取计重梯度
        List<TccLogisticsChannelMaintItem> tccLogisticsChannelMaintItems = new TccLogisticsChannelMaintItem()
                .setMethodId(tccLogisticsChannelMaint.getId())
                .setChannelMaintType(TccLogisticsMethodItemEnum.LogisticsMethodType.JZTD.value)
                .queryList();
        if (tccLogisticsChannelMaintItems == null || tccLogisticsChannelMaintItems.size() == 0){
            return  R.error("未设置物流渠道对应维护的计重范围!");
        }

        //是否有不符合的目的地
        Boolean fbaWarehouseBoo = true;
        Boolean tdjzBoo = true;
        String fbaDeliverItemIds = "";
        for (TccLogisticsPlanAlone tccLogisticsPlanAlone : tccLogisticsPlanAloneList){
            if (tccAdditionalBillingMaintList != null){
                if (tccAdditionalBillingMaintList.size() != 0) {
                    Boolean warehouseCodeBoo = false;
                    for (TccAdditionalBillingMaintTwo tccAdditionalBillingMaintTwo : tccAdditionalBillingMaintList) {
                        //有禁用
                        if (tccAdditionalBillingMaintTwo.getWarehouseCode().equals(tccLogisticsPlanAlone.getFbaWarehouse())) {
                            warehouseCodeBoo = true;
                        }
                    }
                    if (!warehouseCodeBoo) {
                        fbaWarehouseBoo = false;
                        continue;
                    }
                }
            }

            fbaDeliverItemIds = tccLogisticsPlanAlone.getFbaDeliverItemId().toString();
            //箱子数据
            List<TccTicketBox> tccTicketBoxeList = storageMapper.getTicketBoxListByOrder(fbaDeliverItemIds);
            //判断对应的计重是否满足
            BigDecimal weight = getWeight(tccTicketBoxeList,tccLogisticsChannelMaint);

            //计重梯度价（￥/kg） 参照“计重”对应范围的梯度价
            List<TccLogisticsChannelMaintItem> tdjzPrice = tccLogisticsChannelMaintItems.stream().filter(tccLogisticsChannelMaintItem -> weight.compareTo(tccLogisticsChannelMaintItem.getHeavySn()) >= 0
                    && weight.compareTo(tccLogisticsChannelMaintItem.getHeavyEn()) <= 0).collect(Collectors.toList());
            if (tdjzPrice.size() == 0){
                tdjzBoo = false;
                continue;
            }

            String joint = tccLogisticsPlanAlone.getVgsbm() + tccLogisticsPlanAlone.getCck() + tccLogisticsPlanAlone.getFbaWarehouse()
                    +tccLogisticsPlanAlone.getTransportationId();
            if (map.get(joint) != null){
                mapNew.remove(tccLogisticsPlanAlone.getFbaDeliverId().toString());
            }else {
                map.put(joint,tccLogisticsPlanAlone.getFbaDeliverId().toString());
                mapNew.put(tccLogisticsPlanAlone.getFbaDeliverId().toString(),tccLogisticsPlanAlone.getLogsticsWay());
            }
        }

        //查询物流渠道
        //Lambda表达式
        //4.1 通过（键集合）获取值
        Set keySet =mapNew.keySet(); //获取到所有值
        for(Object key : keySet ){
            Object value = mapNew.get(key);
            //查询物流订单
            List<TccLogisticsComprehensive> tccLogisticsComprehensiveList = new TccLogisticsComprehensive().setFbaDeliverId(Long.valueOf(key.toString())).queryList();
            //生成物流发票
            String bid = commonApiService.getCommonNextBid(20485L);
            for (TccLogisticsComprehensive tccLogisticsComprehensive : tccLogisticsComprehensiveList){
                tccLogisticsComprehensive.setLogInvoiceNo(bid);
                //物流渠道为空,取新的物流渠道
                if (value == null){
                    tccLogisticsComprehensive.setLogChannelName(tccLogisticsChannelMaint.getLogsticsChannelName());
                    tccLogisticsComprehensive.setLogChannelId(tccLogisticsChannelMaint.getId());
                    tccLogisticsComprehensive.setFreightMethod(tccLogisticsChannelMaint.getFreightMethod());
                }else {
                    TccFbaLogisticsMethod tccFbaLogisticsMethod = new TccFbaLogisticsMethod().setSourceBid(tccLogisticsComprehensive.getFbaDeliverBid()).setSourceType(1).queryFirst();
                    //查询对应物流服务的渠道
                    TccLogisticsChannelMaint tccLogisticsChannelMaintNew = new TccLogisticsChannelMaint().setLogsticsWay(tccFbaLogisticsMethod.getLogsticsWay()).queryFirst();
                    tccLogisticsComprehensive.setLogChannelName(tccLogisticsChannelMaintNew.getLogsticsChannelName());
                    tccLogisticsComprehensive.setLogChannelId(tccLogisticsChannelMaintNew.getId());
                    tccLogisticsComprehensive.setFreightMethod(tccLogisticsChannelMaintNew.getFreightMethod());
                }
                tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensive);
            }
        }
        if (!fbaWarehouseBoo) {
            return R.error("选择的数据中存在目的地再该渠道不可使用,其余数据已处理!");
        }else if (!tdjzBoo){
            return R.error("选择的数据中存在计重不在物流渠道对应维护的计重范围内,其余数据已处理!");
        }else {
            return R.ok(AddDto.closeAndReload());
        }
    }

    /**
     * 单独发货标记未选择渠道
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R ssmarkNew1(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<Long> idList = new HashSet<>();
        for(String id : strs){
            idList.add(Long.valueOf(id));
        }
        //批量勾选“FBA发货单号”（FBA单条默认整个发货单号都选到）
        String fbaDeliverIds = "";
        for (Long id :idList){
            if ("".equals(fbaDeliverIds)) {
                fbaDeliverIds =  id.toString();
            }else {
                fbaDeliverIds = fbaDeliverIds + "," + id;
            }
        }

        //查询是否重复或者不重复数据（是否绑定数据）
        Map<String,String> map = new HashMap<String, String>();
        //是否需要设置物流渠道的数据
        Map<String,String> mapNew = new HashMap<String, String>();
        List<TccLogisticsPlanAlone> tccLogisticsPlanAloneList = storageMapper.tccLogisticsPlanAloneList(fbaDeliverIds);
        for (TccLogisticsPlanAlone tccLogisticsPlanAlone : tccLogisticsPlanAloneList){
            String joint = tccLogisticsPlanAlone.getVgsbm() + tccLogisticsPlanAlone.getCck() + tccLogisticsPlanAlone.getFbaWarehouse()
                    +tccLogisticsPlanAlone.getTransportationId();
            if (map.get(joint) != null){
                mapNew.remove(tccLogisticsPlanAlone.getFbaDeliverId().toString());
            }else {
                map.put(joint,tccLogisticsPlanAlone.getFbaDeliverId().toString());
                mapNew.put(tccLogisticsPlanAlone.getFbaDeliverId().toString(),tccLogisticsPlanAlone.getLogsticsWay());
            }
        }

        //是否有不符合的目的地
        Boolean fbaWarehouseBoo = true;
        Boolean tdjzBoo = true;
        //Lambda表达式
        //4.1 通过（键集合）获取值
        Set keySet =mapNew.keySet(); //获取到所有值
        for(Object key : keySet ){
            Object value = mapNew.get(key);
            //查询物流订单
            List<TccLogisticsComprehensive> tccLogisticsComprehensiveList = new TccLogisticsComprehensive().setFbaDeliverId(Long.valueOf(key.toString())).queryList();
            //生成物流发票
            String bid = commonApiService.getCommonNextBid(20485L);
            for (TccLogisticsComprehensive tccLogisticsComprehensive : tccLogisticsComprehensiveList){
                tccLogisticsComprehensive.setLogInvoiceNo(bid);
                TccFbaLogisticsMethod tccFbaLogisticsMethod = new TccFbaLogisticsMethod().setSourceBid(tccLogisticsComprehensive.getFbaDeliverBid()).setSourceType(1).queryFirst();
                //查询对应物流服务的渠道
                TccLogisticsChannelMaint tccLogisticsChannelMaintNew = new TccLogisticsChannelMaint().setLogsticsWay(tccFbaLogisticsMethod.getLogsticsWay()).queryFirst();

                if (tccLogisticsChannelMaintNew.getCoefficientWeight() == 0) {
                    tccLogisticsChannelMaintNew.setCoefficientWeight(5000);
                } else {
                    tccLogisticsChannelMaintNew.setCoefficientWeight(6000);
                }

                List<TccAdditionalBillingMaintTwo> tccAdditionalBillingMaintList = new TccAdditionalBillingMaintTwo().setMethodId(tccLogisticsChannelMaintNew.getId()).queryList();

                //获取计重梯度
                List<TccLogisticsChannelMaintItem> tccLogisticsChannelMaintItems = new TccLogisticsChannelMaintItem()
                        .setMethodId(tccLogisticsChannelMaintNew.getId())
                        .setChannelMaintType(TccLogisticsMethodItemEnum.LogisticsMethodType.JZTD.value)
                        .queryList();
                if (tccLogisticsChannelMaintItems == null || tccLogisticsChannelMaintItems.size() == 0){
                    return  R.error("未设置物流渠道对应维护的计重范围!");
                }
                //获取目的地
                TccFbaBoxUpInfo tccFbaBoxUpInfo = new TccFbaBoxUpInfo().setFbaNo(tccLogisticsComprehensive.getFbaNo()).queryFirst();

                String fbaDeliverItemIds = "";
                if (tccAdditionalBillingMaintList != null){
                    if (tccAdditionalBillingMaintList.size() != 0) {
                        Boolean warehouseCodeBoo = false;
                        for (TccAdditionalBillingMaintTwo tccAdditionalBillingMaintTwo : tccAdditionalBillingMaintList) {
                            //有禁用
                            if (tccAdditionalBillingMaintTwo.getWarehouseCode().equals(tccFbaBoxUpInfo.getFbaWarehouse())) {
                                warehouseCodeBoo = true;
                            }
                        }
                        if (!warehouseCodeBoo) {
                            fbaWarehouseBoo = false;
                            continue;
                        }
                    }
                }

                fbaDeliverItemIds = tccLogisticsComprehensive.getFbaDeliverItemId().toString();
                //箱子数据
                List<TccTicketBox> tccTicketBoxeList = storageMapper.getTicketBoxListByOrder(fbaDeliverItemIds);
                //判断对应的计重是否满足
                BigDecimal weight = getWeight(tccTicketBoxeList,tccLogisticsChannelMaintNew);

                //计重梯度价（￥/kg） 参照“计重”对应范围的梯度价
                List<TccLogisticsChannelMaintItem> tdjzPrice = tccLogisticsChannelMaintItems.stream().filter(tccLogisticsChannelMaintItem -> weight.compareTo(tccLogisticsChannelMaintItem.getHeavySn()) >= 0
                        && weight.compareTo(tccLogisticsChannelMaintItem.getHeavyEn()) <= 0).collect(Collectors.toList());
                if (tdjzPrice.size() == 0){
                    tdjzBoo = false;
                    continue;
                }

                tccLogisticsComprehensive.setLogChannelName(tccLogisticsChannelMaintNew.getLogsticsChannelName());
                tccLogisticsComprehensive.setLogChannelId(tccLogisticsChannelMaintNew.getId());
                tccLogisticsComprehensive.setFreightMethod(tccLogisticsChannelMaintNew.getFreightMethod());
                tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensive);
            }
        }
        if (!fbaWarehouseBoo) {
            return R.error("选择的数据中存在目的地再该渠道不可使用,其余数据已处理!");
        }else if (!tdjzBoo){
            return R.error("选择的数据中存在计重不在物流渠道对应维护的计重范围内,其余数据已处理!");
        }else {
            return R.ok(AddDto.closeAndReload());
        }
    }

    /**
     * 重新发货标记
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R cxmark(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<String> idList = new HashSet<>();
        for(String bid : strs){
            idList.add(bid);
        }

        for (String bid :idList){
           //查询物流发票号的计划数据
            List<TccLogisticsComprehensive> tccLogisticsComprehensiveList = new TccLogisticsComprehensive().setLogInvoiceNo(bid).where("A.Status != 0").queryList();
            for (TccLogisticsComprehensive tccLogisticsComprehensive : tccLogisticsComprehensiveList){
                if (tccLogisticsComprehensive.getStatus() != TccLogisticsComprehensiveEnum.Status.EMPTY.value){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("只允许物流状态为空的数据,请核实后在操作!");
                }

                if (tccLogisticsComprehensive.getLogInvoiceNo() == null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("勾选的数据中存在物流发票号为空的数据，不允许重新发货标记,请核实后在操作!");
                }
                //查询对应物流服务的渠道
                storageMapper.updateCxmark(tccLogisticsComprehensive.getId());
            }
        }

        return R.ok(AddDto.closeAndReload());
    }

    /**
     * 物流计划取消
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R qxPlan(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<String> idList = new HashSet<>();
        for(String bid : strs){
            idList.add(bid);
        }

        for (String bid :idList){
            //查询物流发票号的计划数据
            List<TccLogisticsComprehensive> tccLogisticsComprehensiveList = new TccLogisticsComprehensive().setFbaDeliverBid(bid).where("A.Status != 0").queryList();
            for (TccLogisticsComprehensive tccLogisticsComprehensive : tccLogisticsComprehensiveList){
                if (tccLogisticsComprehensive.getStatus() != TccLogisticsComprehensiveEnum.Status.EMPTY.value){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("只允许物流状态为空的数据,请核实后在操作!");
                }

                if (tccLogisticsComprehensive.getLogInvoiceNo() != null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("只允许物流发票号为空的数据,请核实后在操作!");
                }
                tccLogisticsComprehensive.setStatus(TccLogisticsComprehensiveEnum.Status.CANCEL.value);
                tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensive);

                List<TccFbaDeliver> tccFbaDeliverList = new TccFbaDeliver().setBid(bid).queryList();
                for (TccFbaDeliver tccFbaDeliver : tccFbaDeliverList){
                    tccFbaDeliver.setStatus(TccFbaDeliverEnum.Status.TRANSSHIPPED.value);
                    tccFbaDeliverMapper.update(tccFbaDeliver);
                }
            }
        }

        return R.ok(AddDto.closeAndReload());
    }

    /**
     * 拼票发货标记判断是否通过,并且返回拼票预测
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R ppMark(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<Long> idList = new HashSet<>();
        for(String id : strs){
            idList.add(Long.valueOf(id));
        }
        //批量勾选“FBA发货单号”（FBA单条默认整个发货单号都选到）
        String fbaDeliverIds = "";
        for (Long id :idList){
            if ("".equals(fbaDeliverIds)) {
                fbaDeliverIds =  id.toString();
            }else {
                fbaDeliverIds = fbaDeliverIds + "," + id;
            }
        }
        int count = storageMapper.logsticsWayCount(fbaDeliverIds);
        if (count > 1){
            return R.error("勾选的发货单中，物流服务需要一致，请确认；");
        }

        List<String> fbaWarehouseAddrList = storageMapper.getFbaWarehouseAddrCount(fbaDeliverIds);
        if (fbaWarehouseAddrList.size() > 1){
            return R.error("勾选的发货单中，目的地需要一致，请确认；");
        }

        List<TccLogisticsPlanAlone> tccLogisticsPlanAloneList = storageMapper.tccLogisticsPlanAloneList(fbaDeliverIds);

        Map<String,String> mapBoolean = new HashMap<String, String>();
        mapBoolean.put("cck",tccLogisticsPlanAloneList.get(0).getCck());
        mapBoolean.put("fbaWarehouseAddr",fbaWarehouseAddrList.get(0));
        mapBoolean.put("destinationCountryCode",tccLogisticsPlanAloneList.get(0).getDestinationCountryCode());
        mapBoolean.put("transportationId",tccLogisticsPlanAloneList.get(0).getTransportationId().toString());
        mapBoolean.put("nameLogsticsClearance",tccLogisticsPlanAloneList.get(0).getNameLogsticsClearance());

        return R.ok(mapBoolean);
    }

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R ppMarkNew(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<Long> idList = new HashSet<>();
        for(String id : strs){
            idList.add(Long.valueOf(id));
        }
        //批量勾选“FBA发货单号”（FBA单条默认整个发货单号都选到）
        String fbaDeliverIds = "";
        for (Long id :idList){
            if ("".equals(fbaDeliverIds)) {
                fbaDeliverIds =  id.toString();
            }else {
                fbaDeliverIds = fbaDeliverIds + "," + id;
            }
        }


        TccLogisticsChannelMaint tccLogisticsChannelMaintNew = new TccLogisticsChannelMaint().setId(Long.valueOf(params.get("logsticsChannelId").toString())).queryFirst();
        if (tccLogisticsChannelMaintNew.getCoefficientWeight() == 0) {
            tccLogisticsChannelMaintNew.setCoefficientWeight(5000);
        } else {
            tccLogisticsChannelMaintNew.setCoefficientWeight(6000);
        }

        //获取计重梯度
        List<TccLogisticsChannelMaintItem> tccLogisticsChannelMaintItems = new TccLogisticsChannelMaintItem()
                .setMethodId(tccLogisticsChannelMaintNew.getId())
                .setChannelMaintType(TccLogisticsMethodItemEnum.LogisticsMethodType.JZTD.value)
                .queryList();
        if (tccLogisticsChannelMaintItems == null || tccLogisticsChannelMaintItems.size() == 0){
            return  R.error("未设置物流渠道对应维护的计重范围!");
        }

        List<TccAdditionalBillingMaintTwo> tccAdditionalBillingMaintList = new TccAdditionalBillingMaintTwo().setMethodId(tccLogisticsChannelMaintNew.getId()).queryList();

        //是否需要设置物流渠道的数据
        Map<Long,List<TccLogisticsPlanAlone>> mapNew = new HashMap<Long, List<TccLogisticsPlanAlone>>();
        List<TccLogisticsPlanAlone> tccLogisticsPlanAloneList = storageMapper.tccLogisticsPlanAloneList(fbaDeliverIds);
        //是否有不符合的目的地
        Boolean fbaWarehouseBoo = true;
        BigDecimal weightTol = BigDecimal.ZERO;
        String fbaDeliverItemIds = "";
        for (TccLogisticsPlanAlone tccLogisticsPlanAlone : tccLogisticsPlanAloneList){
            if (tccAdditionalBillingMaintList != null){
                if (tccAdditionalBillingMaintList.size() != 0) {
                    Boolean warehouseCodeBoo = false;
                    for (TccAdditionalBillingMaintTwo tccAdditionalBillingMaintTwo : tccAdditionalBillingMaintList) {
                        //有禁用
                        if (tccAdditionalBillingMaintTwo.getWarehouseCode().equals(tccLogisticsPlanAlone.getFbaWarehouse())) {
                            warehouseCodeBoo = true;
                        }
                    }
                    if (!warehouseCodeBoo) {
                        fbaWarehouseBoo = false;
                        continue;
                    }
                }
            }
            fbaDeliverItemIds = tccLogisticsPlanAlone.getFbaDeliverItemId().toString();
            //箱子数据
            List<TccTicketBox> tccTicketBoxeList = storageMapper.getTicketBoxListByOrder(fbaDeliverItemIds);
            //判断对应的计重是否满足
            BigDecimal weight = getWeight(tccTicketBoxeList,tccLogisticsChannelMaintNew);
            weightTol = weightTol.add(weight);

            if (mapNew.get(tccLogisticsPlanAlone.getFbaDeliverId()) != null){
                List<TccLogisticsPlanAlone> tccLogisticsPlanAloneListNew = mapNew.get(tccLogisticsPlanAlone.getFbaDeliverId());
                tccLogisticsPlanAloneListNew.add(tccLogisticsPlanAlone);
                mapNew.put(tccLogisticsPlanAlone.getFbaDeliverId(),tccLogisticsPlanAloneListNew);
            }else {
                List<TccLogisticsPlanAlone> tccLogisticsPlanAloneListNew = new ArrayList<>();
                tccLogisticsPlanAloneListNew.add(tccLogisticsPlanAlone);
                mapNew.put(tccLogisticsPlanAlone.getFbaDeliverId(),tccLogisticsPlanAloneListNew);
            }
        }

        //计重梯度价（￥/kg） 参照“计重”对应范围的梯度价
        BigDecimal finalWeightTol = weightTol;
        List<TccLogisticsChannelMaintItem> tdjzPrice = tccLogisticsChannelMaintItems.stream().filter(tccLogisticsChannelMaintItem -> finalWeightTol.compareTo(tccLogisticsChannelMaintItem.getHeavySn()) >= 0
                && finalWeightTol.compareTo(tccLogisticsChannelMaintItem.getHeavyEn()) <= 0).collect(Collectors.toList());
        if (tdjzPrice.size() == 0){
            return R.error("选择的数据中存在计重合计:"+finalWeightTol+",不在物流渠道对应维护的计重范围内,核实后再操作!");
        }

        //Lambda表达式
        //4.1 通过（键集合）获取值
        Set keySet =mapNew.keySet(); //获取到所有值
        String bid = commonApiService.getCommonNextBid(20485L);
        for(Object key : keySet ){
            //查询物流订单
            List<TccLogisticsPlanAlone> tccLogisticsComprehensiveList = mapNew.get(key);
            //生成物流发票
            for (TccLogisticsPlanAlone tccLogisticsPlanAlone : tccLogisticsComprehensiveList){
                TccLogisticsComprehensive tccLogisticsComprehensive = new TccLogisticsComprehensive();
                tccLogisticsComprehensive.setId(tccLogisticsPlanAlone.getId());
                tccLogisticsComprehensive.setLogInvoiceNo(bid);
                tccLogisticsComprehensive.setLogChannelName(tccLogisticsChannelMaintNew.getLogsticsChannelName());
                tccLogisticsComprehensive.setLogChannelId(tccLogisticsChannelMaintNew.getId());
                tccLogisticsComprehensive.setFreightMethod(tccLogisticsChannelMaintNew.getFreightMethod());
                tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensive);
            }
        }
        if (!fbaWarehouseBoo){
            return R.error("选择的数据中存在目的地再该渠道不可使用,其余数据已处理!");
        }else {
            return R.ok();
        }
    }

    /**
     * 获取拼票预测数据
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R ppMarkTicket(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<Long> idList = new HashSet<>();
        for(String id : strs){
            idList.add(Long.valueOf(id));
        }
        //批量勾选“FBA发货单号”（FBA单条默认整个发货单号都选到）
        String fbaDeliverIds = "";
        for (Long id :idList){
            if ("".equals(fbaDeliverIds)) {
                fbaDeliverIds =  id.toString();
            }else {
                fbaDeliverIds = fbaDeliverIds + "," + id;
            }
        }

        TccLogisticsChannelMaint tccLogisticsChannelMaint = new TccLogisticsChannelMaint().setId(Long.valueOf(params.get("id").toString())).queryFirst();

        if (tccLogisticsChannelMaint.getCoefficientWeight() == 0) {
            tccLogisticsChannelMaint.setCoefficientWeight(5000);
        } else {
            tccLogisticsChannelMaint.setCoefficientWeight(6000);
        }

        //材质梯度
        List<TccLogisticsChannelMaintItemSon> czTdList = new TccLogisticsChannelMaintItemSon()
                .setMethodId(tccLogisticsChannelMaint.getId())
                .queryList();

        //运输类型快递以外都是物流 0.快递|1.物流
        Integer transportation = 0;
        if (tccLogisticsChannelMaint.getTransportationId() != 0) {
            transportation = 1;
        }

        //箱子数据
        List<TccTicketBox> tccTicketBoxeList = storageMapper.getTicketBoxList(fbaDeliverIds);
        //获取品名信息
        List<TccTicketBrandName> tccTicketBrandNameList = storageMapper.getTccTicketBrandNameList(fbaDeliverIds);

        //实重（kg）（拼）
        BigDecimal weightRealPp = BigDecimal.ZERO;
        //抛重（kg）
        BigDecimal weightVolPp = BigDecimal.ZERO;
        //计重（kg）
        BigDecimal weightCalPp = BigDecimal.ZERO;
        for (TccTicketBox tccTicketBox : tccTicketBoxeList){
            //0.快递|1.物流
            if (transportation == 0) {
                //实重（kg）（拼） 所有箱---MAX（实重，单箱起重）先约分---在相加
                weightRealPp = weightRealPp.add(
                        ruleReduction(tccLogisticsChannelMaint, tccTicketBox.getBoxWeight())
                                .max(tccLogisticsChannelMaint.getWeightCalBySingle())
                );
                //抛重（kg）（拼） = 所有箱---MAX（抛重，单箱起重）先约分---在相加
                weightVolPp = weightVolPp.add(ruleReduction(tccLogisticsChannelMaint, (tccTicketBox.getBoxLong().multiply(tccTicketBox.getBoxWide()).multiply(tccTicketBox.getBoxHigh()))
                        .divide(new BigDecimal(tccLogisticsChannelMaint.getCoefficientWeight()), 2, RoundingMode.HALF_UP)));
            }else {
                //实重（kg）（拼） =所有箱---MAX（实重，单箱起重）先相加---在约分
                weightRealPp = weightRealPp.add(
                        tccTicketBox.getBoxWeight()).max(tccLogisticsChannelMaint.getWeightCalBySingle()
                );
                //抛重（kg） （拼）= 所有箱---MAX（抛重，单箱起重）先相加---在约分
                weightVolPp = weightVolPp.add((tccTicketBox.getBoxLong().multiply(tccTicketBox.getBoxWide()).multiply(tccTicketBox.getBoxHigh()))
                        .divide(new BigDecimal(tccLogisticsChannelMaint.getCoefficientWeight()), 2, RoundingMode.HALF_UP));
            }
        }

        //0.快递|1.物流
        if (transportation == 1) {
            //在约分
            weightRealPp = ruleReduction(tccLogisticsChannelMaint,weightRealPp);
            weightVolPp = ruleReduction(tccLogisticsChannelMaint,weightVolPp);
        }

        //计重（kg）（拼） = MAX【实重（kg）（拼），抛重（kg）（拼）】
        weightCalPp = weightRealPp.max(weightVolPp);

        //品名数量（拼） = 品名数（参照商品品名）-免费品名数
        Integer numProName = tccTicketBrandNameList.size() - tccLogisticsChannelMaint.getFreeProNameNum();
        numProName = numProName> 0 ? numProName: 0;

        //查询发货单对应的费用明细
        List<Map<String, Object>> tccFbaFeeDetailsList = new TccFbaFeeDetails().setSourceType(1)
                .addField("(SELECT COUNT(1) FROM TCC_FbaDeliverSon WHERE Pbid = A.sourceBid) boxNum")
                .addLeftJoin("TCC_FbaDeliver B ON B.bid = A.sourceBid")
                .addLeftJoin("TCC_FbaLogisticsMethod C ON C.sourceBid = B.bid AND C.sourceType = 1")
                .addField("C.jfFee,C.pzFee,C.additionalBilling")
                .where("B.id IN (" + fbaDeliverIds + ")")
                .queryMap();

        //销售费用（总）=列表字段--物流实际费用（总）之和
        BigDecimal priceTranPredictTol = BigDecimal.ZERO;
        //品名附加费（总）=列表字段--品名附加费之和
        BigDecimal priceProNameExtraPredictTol = BigDecimal.ZERO;
        //材质附加费（总） = 列表字段--材质附加费之和
        BigDecimal priceQualityExtraPredictTol = BigDecimal.ZERO;
        for (Map<String, Object> map : tccFbaFeeDetailsList){
            priceTranPredictTol = priceTranPredictTol.add(new BigDecimal(map.get("priceTranPredict").toString()));
            priceProNameExtraPredictTol = priceProNameExtraPredictTol.add(new BigDecimal(map.get("priceProNameExtraPredict").toString()));
            priceQualityExtraPredictTol = priceQualityExtraPredictTol.add(new BigDecimal(map.get("priceQualityExtraPredict").toString()));
        }
        //材质名称（中文）（拼）
        String czCnPp = "";
        //材质费用拼
        BigDecimal czFeePp = BigDecimal.ZERO;
        for (TccTicketBrandName tccTicketBrandName : tccTicketBrandNameList) {
            //判断是否是混合材质
            if (tccTicketBrandName.getNameMaterialCn().indexOf(",") == -1) {
                //赋值材质附加费(取最大值)
                for (int j = 0; j < czTdList.size(); j++) {
                    if (czTdList.get(j).getMaterialNameCn().equals(tccTicketBrandName.getNameMaterialCn())) {
                        if (czTdList.get(j).getAdditionalMaterialBilling().compareTo(czFeePp) > 0) {
                            czFeePp = (czTdList.get(j).getAdditionalMaterialBilling());
                            czCnPp = (czTdList.get(j).getMaterialNameCn());
                        }
                    }
                }
            } else {
                String[] nameMaterialCnList = tccTicketBrandName.getNameMaterialCn().split(",");
                for (String nameMaterialCn : nameMaterialCnList) {
                    for (int j = 0; j < czTdList.size(); j++) {
                        if (czTdList.get(j).getMaterialNameCn().equals(nameMaterialCn)) {
                            if (czTdList.get(j).getAdditionalMaterialBilling().compareTo(czFeePp) > 0) {
                                czFeePp = (czTdList.get(j).getAdditionalMaterialBilling());
                                czCnPp = (czTdList.get(j).getMaterialNameCn());
                            }
                        }
                    }
                }
            }
        }

        Map<String,Object> mapBoolean = new HashMap<String, Object>();
        //列表数据
        mapBoolean.put("tccFbaFeeDetailsList",tccFbaFeeDetailsList);
        mapBoolean.put("restrictionShipment","限制发货");
        //拼票计重（kg）
        mapBoolean.put("ticketWeight",weightCalPp);
        //拼票品名数量
        mapBoolean.put("proNameNum",numProName);
        //销售费用（总）
        mapBoolean.put("priceTranPredictTol",priceTranPredictTol);
        //计重（kg）（拼）
        mapBoolean.put("weightCalPp",weightCalPp);
        //实重（kg）（拼）
        mapBoolean.put("weightRealPp",weightRealPp);
        //抛重（kg）（拼）
        mapBoolean.put("weightVolPp",weightVolPp);
        //品名数量（拼）
        mapBoolean.put("numProName",numProName);
        //品名附加费（总）
        mapBoolean.put("priceProNameExtraPredictTol",priceProNameExtraPredictTol);
        //材质名称（中文）（拼）
        mapBoolean.put("czCnPp",czCnPp);
        //材质附加费（总）
        mapBoolean.put("priceQualityExtraPredictTol",priceQualityExtraPredictTol);
        if (weightCalPp.compareTo(tccLogisticsChannelMaint.getSinglePassCrane()) >= 0 && numProName <= tccLogisticsChannelMaint.getMaxProNameNum()){
            //计重梯度+抛重梯度
            List<TccLogisticsChannelMaintItem> tccLogisticsChannelMaintItems = new TccLogisticsChannelMaintItem()
                    .setMethodId(tccLogisticsChannelMaint.getId())
                    .queryList();
            //计重梯度
            List<TccLogisticsChannelMaintItem> jzTdList = tccLogisticsChannelMaintItems.stream().filter(tccLogisticsChannelMaintItem ->
                    TccLogisticsMethodItemEnum.LogisticsMethodType.JZTD.value.equals(tccLogisticsChannelMaintItem.getChannelMaintType())).collect(Collectors.toList());

            //计重梯度价（￥/kg） 参照“计重”对应范围的梯度价
            BigDecimal finalWeightCal = weightCalPp;
            List<TccLogisticsChannelMaintItem> tdjzPrice = jzTdList.stream().filter(tccLogisticsChannelMaintItem -> finalWeightCal.compareTo(tccLogisticsChannelMaintItem.getHeavySn()) >= 0
                    && finalWeightCal.compareTo(tccLogisticsChannelMaintItem.getHeavyEn()) <= 0).collect(Collectors.toList());

            //计重
            BigDecimal jfFee = BigDecimal.ZERO;
            if (tdjzPrice.size() != 0) {
                jfFee = tdjzPrice.get(0).getPrice();
            }

            //抛重梯度
            List<TccLogisticsChannelMaintItem> pzTdList = tccLogisticsChannelMaintItems.stream().filter(tccLogisticsChannelMaintItem ->
                    TccLogisticsMethodItemEnum.LogisticsMethodType.PZTD.value.equals(tccLogisticsChannelMaintItem.getChannelMaintType())).collect(Collectors.toList());

            BigDecimal pzFee = BigDecimal.ZERO;
            BigDecimal finalWeightVol = weightVolPp;
            List<TccLogisticsChannelMaintItem> tdPzPrice = pzTdList.stream().filter(tccLogisticsChannelMaintItem -> finalWeightVol.compareTo(tccLogisticsChannelMaintItem.getHeavySn()) >= 0
                    && finalWeightVol.compareTo(tccLogisticsChannelMaintItem.getHeavyEn()) <= 0).collect(Collectors.toList());
            //抛重
            if (tdPzPrice.size() != 0) {
                pzFee = tdPzPrice.get(0).getPrice();
            }

            //目的地
            List<TccAdditionalBillingMaint> tccAdditionalBillingMaintList = new TccAdditionalBillingMaint().setMethodId(tccLogisticsChannelMaint.getId()).queryList();

            //目的地
            String finalWarehouse = params.get("fbaWarehouseAddr").toString();
            //目的地附加计费（￥/kg）】 TODO
            BigDecimal additionalBilling = BigDecimal.ZERO;
            List<TccAdditionalBillingMaint> tccAdditionalBillingListNew = tccAdditionalBillingMaintList.stream().filter(
                    tccAdditionalBilling -> finalWarehouse.equals(tccAdditionalBilling.getWarehouseCode())
            ).collect(Collectors.toList());
            //目的地 仓库代码满足直接取 反之 取邮编首数字开头的比并且仓库为空
            if (tccAdditionalBillingListNew.size() != 0) {
                additionalBilling = tccAdditionalBillingListNew.get(0).getAdditionalBilling();
            } else {
                tccAdditionalBillingListNew = tccAdditionalBillingMaintList.stream().filter(tccAdditionalBilling ->
                        (tccAdditionalBilling.getWarehouseCode() == null || tccAdditionalBilling.getWarehouseCode().equals("")) && tccAdditionalBilling.getFirstPostalCode()!=null && finalWarehouse.startsWith(tccAdditionalBilling.getFirstPostalCode())
                ).collect(Collectors.toList());
                if (tccAdditionalBillingListNew.size() != 0) {
                    additionalBilling = tccAdditionalBillingListNew.get(0).getAdditionalBilling();
                }
            }

            //计重费用（拼） = 计重（kg）*（计重梯度价（￥/kg）+目的地附加计费（￥/kg））
           BigDecimal priceTranCalWeight = weightCalPp.multiply(jfFee.add(additionalBilling)).setScale(2, BigDecimal.ROUND_HALF_UP);

            //品名附加费（拼） = 【品名数量（拼】*品名附加费
            BigDecimal priceProNameExtraPredictPp =  new BigDecimal(numProName).multiply(tccLogisticsChannelMaint.getAdditionalStandardAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);

            //材质附加费（拼） = 计重（kg）（拼）*材质附加费标准
            BigDecimal priceQualityExtraPredict = (czFeePp.multiply(weightCalPp)).setScale(2, BigDecimal.ROUND_HALF_UP);

            //拼票费用（总） = 计重费用（拼）+品名附加费（总）+材质附加费（拼）+清关费（物流渠道名称引用）
            BigDecimal ticketFee =  priceTranCalWeight.add(priceProNameExtraPredictTol).add(priceQualityExtraPredict).add(tccLogisticsChannelMaint.getClearanceOpeAmount());

            //发货盈亏 盈利= 拼票费用（总）＜销售费用（总） 反之亏损
            String profitLossShipment = "亏损";
            if (ticketFee.compareTo(priceTranPredictTol) == -1){
                profitLossShipment = "盈利";
            }
            BigDecimal profitLoss = BigDecimal.ZERO;
            if (ticketFee.compareTo(BigDecimal.ZERO) != 0){
                //盈亏率 = 【拼票费用（总）-销售费用（总）】/拼票费用（总）
                profitLoss = (ticketFee.subtract(priceTranPredictTol)).divide(ticketFee,2,BigDecimal.ROUND_HALF_UP);
            }

            mapBoolean.put("restrictionShipment","空");
            //单票起重（kg）
            mapBoolean.put("singlePassCrane",tccLogisticsChannelMaint.getSinglePassCrane());
            //单票品名上限
            mapBoolean.put("maxProNameNum",tccLogisticsChannelMaint.getMaxProNameNum());
            //盈亏率 =
            mapBoolean.put("profitLoss",profitLoss + "%");
            //发货盈亏
            mapBoolean.put("profitLossShipment",profitLossShipment);
            //拼票费用（总）
            mapBoolean.put("ticketFee",ticketFee);
            //计重费用（拼）
            mapBoolean.put("priceTranCalWeight",priceTranCalWeight);
            //计重梯度价（￥/kg）
            mapBoolean.put("jfFee",jfFee);
            //目的地附加计费（￥/kg）
            mapBoolean.put("additionalBilling",additionalBilling);
            //品名附加费（拼）
            mapBoolean.put("priceProNameExtraPredictPp",priceProNameExtraPredictPp);
            //材质附加费（拼）
            mapBoolean.put("priceQualityExtraPredict",priceQualityExtraPredict);
        }

        return R.ok(mapBoolean);
    }

    /**
     * 物流订单生成
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R cOrder(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<String> bidList = new HashSet<>();
        for(String bid : strs){
            bidList.add(bid);
        }

        //批量勾选“FBA发货单号”（FBA单条默认整个发货单号都选到）
        Set<String> fbaDeliverBids = new HashSet<>();

        String logisticsMarkingBid = params.get("logisticsMarkingBid") == null ? null : params.get("logisticsMarkingBid").toString();
        List<TccLogisticsComprehensive> tccLogisticsComprehensiveList = storageMapper.getLogisticsComByBid(bidList);

        if (logisticsMarkingBid != null){
            if (new TccLogisticsComprehensive().setLogisticsMarkingBid(logisticsMarkingBid).where("A.logOrderProfit != 0").count() > 0){
                return R.error("该物流标记号("+logisticsMarkingBid+")已出现物流费用的计算，不让标记!");
            }
        }

        //根据渠道来分类
        Map<String, List<TccLogisticsComprehensive>> dataMap = new HashMap<>();
        List<TccLogisticsComprehensive> tccLogisticsComprehensiveListNew;
        for (TccLogisticsComprehensive tccLogisticsComprehensive : tccLogisticsComprehensiveList){
            if (tccLogisticsComprehensive.getLogInvoiceNo() == null || tccLogisticsComprehensive.getLogChannelName() == null){
                return R.error("存在未进行发货标记的数据，请确认!");
            }
            if (tccLogisticsComprehensive.getStatus() != 1) {
                return R.error("只允许物流状态为空的数据,请核实后在操作!");
            }
            tccLogisticsComprehensive.setLogisticsMarkingBid(logisticsMarkingBid);
            if (dataMap.get(tccLogisticsComprehensive.getLogChannelName()) == null){
                tccLogisticsComprehensiveListNew = new ArrayList<>();
                tccLogisticsComprehensiveListNew.add(tccLogisticsComprehensive);
            }else {
                tccLogisticsComprehensiveListNew = dataMap.get(tccLogisticsComprehensive.getLogChannelName());
                tccLogisticsComprehensiveListNew.add(tccLogisticsComprehensive);
            }
            dataMap.put(tccLogisticsComprehensive.getLogChannelName(),tccLogisticsComprehensiveListNew);

            fbaDeliverBids.add(tccLogisticsComprehensive.getFbaDeliverBid());
        }

        //批量修改物流发货id
        storageMapper.updateFbaDeliverById(fbaDeliverBids);

        Set keySet =dataMap.keySet(); //获取到所有值
        for(Object key : keySet ) {
            List<TccLogisticsComprehensive> tccLogisticsComprehensives = dataMap.get(key);
            tccLogisticsComprehensiveOrderService.add(tccLogisticsComprehensives);
        }
        return R.ok(AddDto.closeAndReload());
    }

    private BigDecimal ruleReduction(TccLogisticsChannelMaint tccLogisticsChannelMaint,BigDecimal amount){
        //约分规则
        if (tccLogisticsChannelMaint.getDivisionalRule() == TccLogisticsMethodEnum.DivisionalRule.INTO1.value){
            amount = new BigDecimal(Math.ceil(amount.doubleValue()));
        }else if (tccLogisticsChannelMaint.getDivisionalRule() == TccLogisticsMethodEnum.DivisionalRule.INTO_05_1.value){
            amount = FbaUtils.precision(amount);
        }
        return amount;
    }

    /**
     * 计算计重
     */
    private BigDecimal getWeight(List<TccTicketBox> tccTicketBoxeList,TccLogisticsChannelMaint tccLogisticsChannelMaintByMain){
        //实重（kg）（拼）
        BigDecimal weightRealPp = BigDecimal.ZERO;
        //抛重（kg）
        BigDecimal weightVolPp = BigDecimal.ZERO;
        for (TccTicketBox tccTicketBox : tccTicketBoxeList){
                //实重（kg）（拼） 所有箱---相加
                weightRealPp = weightRealPp.add(
                        tccTicketBox.getBoxWeight()
                );
                //抛重（kg）（拼） = 所有箱---在相加
                weightVolPp = weightVolPp.add( (tccTicketBox.getBoxLong().multiply(tccTicketBox.getBoxWide()).multiply(tccTicketBox.getBoxHigh()))
                        .divide(new BigDecimal(tccLogisticsChannelMaintByMain.getCoefficientWeight()), 2, RoundingMode.HALF_UP));
        }

        //发票计重（kg）
        BigDecimal weightCalPp = BigDecimal.ZERO;
        //MAX【FBA实重（kg），FBA抛重（kg）】
        weightCalPp = weightRealPp.max(weightVolPp);

        return weightCalPp;
    }
}
